<template>
  <div class="login-container">
    <el-form ref="form" :model="form" label-width="100px">
      <el-form-item label="用户名" prop="username" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
        <el-input v-model="form.password" type="password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleLogin">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    async handleLogin() {
      try {
        const response = await axios.post('http://localhost:8000/api/token/', {
          username: this.form.username,
          password: this.form.password
        })
        const token = response.data.access // 假设返回的 token 在 response.data.token 中
        localStorage.setItem('token', token) // 保存 token 到本地存储
        this.$message.success('登录成功')
        this.$router.push('/hello') // 登录成功后跳转到 HelloWorld 组件
      } catch (error) {
        this.$message.error('登录失败: ' + (error.response.data.detail || '未知错误'))
      }
    }
  }
}
</script>

  <style scoped>
  .login-container {
    max-width: 400px;
    margin: 100px auto;
  }
  </style>
